<?php

namespace app\admin\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Admin extends Model
{
    use SoftDelete;

    //软删除

    //声明表名
    protected $table = 'pyg_admin';

    //查询管理员详细信息
    public static function getAdminInfo($where)
    {
        //查询一条
        return self::where($where)->find();
//        //查询多条
//        self::select();
    }


    //更新管理员
    public static function modifyAdminInfo($data, $id)
    {
        //    * @param array      $data  数据数组
        //    * @param array      $where 更新条件
        //    * @param array|true $field 允许字段
        return self::update($data, ['id' => $id], true);
    }

    //查询所有管理员数据
    public static function getAdminAll($where, $page, $limit)
    {
//     page
//    * @param mixed $page     页数
//    * @param mixed $listRows 每页数量
        return self::where('nickname', 'like', "%$where%")->page($page, $limit)->select();
    }

    //统计所有管理员数量
    public static function getAdminCount($where)
    {
//     page
//    * @param mixed $page     页数
//    * @param mixed $listRows 每页数量
        return self::where('nickname', 'like', "%$where%")->count();
    }

    //删除
    public static function deleteAdminInfo($id)
    {
        return self::destroy($id);
    }

    //查询用户对应权限
    public static function getUserNodeAll($id)
    {
        $field = 'u.id as userId,u.username,r.role_name,n.*';

        $userNode = self::alias('u')
            ->field($field)
            ->join('pyg_admin_role ur', 'u.id = ur.uid')
            ->join('pyg_role r', 'ur.rid = r.id')
            ->join('pyg_role_node rn', 'r.id = rn.rid')
            ->join('pyg_node n', 'rn.nid = n.id ')
            ->where('u.id', $id)
            ->order('n.order', 'ASC')
            ->select();

        return self::getTree($userNode, 0);
    }

    //展示层级权限
    public static function getTree($data, $pid = 0)
    {
        $result = []; //权限数组
        if (empty($data)) {//如果权限数组为空，则直接返回
            return $result;
        }

        foreach ($data as $key => $item) {
            if ($item['pid'] == $pid) {
                //找父级
                //$item['pid']   5 0 6 0 13 13 0 16 16    $pid 0
                //$item['pid']   5 0 6 0 13 13 0 16 16    $pid 5
                $item['child'] = self::getTree($data, $item['id']); // $pid  5
                $result[] = $item;
            }
        }

        return $result;
    }

}
